import {createApp, ref} from 'vue'
import App from './App.vue'
import router, {loadDynamicMenus} from './router'
import ElementPlus from 'element-plus'
import {createPinia, defineStore} from 'pinia'
import 'element-plus/dist/index.css'
import './css/global.css';
import './styles/main.scss'
import * as ElementPlusIconsVue from '@element-plus/icons-vue'

import {getUserInfo} from "@/utils/system";
import {initAxiosInterceptors} from "@/utils/request";
import {message} from "@/utils/ElmessasgeUtils";
import type {MenuTreeItem} from "@/type/common/MenuRouter";
import {getSysConfig} from "@/api/system/sysConfig";
import {getUserStorageConfig} from "@/api/documentManage/config";

const app = createApp(App)

const isAppCollapsed = ref(false);
const MainMenuItems = ref<MenuTreeItem[]>([]);



// 注册所有图标
function registerIcon() {
    for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
        app.component(key, component)
    }
}


const pinia = createPinia()
app.use(pinia);
app.use(ElementPlus);

// 主Pinia库
const useMainStore = defineStore('mainStore', () => {
    const fileStorageType = ref() // 文件存储类型，true为minio，false为本地
    const systemName = ref()
    const localFileStoragePath = ref()
    const systemDescription = ref()

    // 获取配置数据的方法
    const updateConfig = async (des: string) => {
        console.log(des + " 获取状态变量信息 开始")
        try {
            let res1: any = await getSysConfig("sysName")
            if (res1.data.code == 200) {
                systemName.value = res1.data.data
                console.log(1, systemName.value)
            } else {
                message("获取系统名称失败", 'error')
            }

            let res2: any = await getUserStorageConfig(getUserInfo().userId)
            if (res2.data.code === 200) {
                fileStorageType.value = res2.data.data.storageType === 0
                localFileStoragePath.value = res2.data.data.storagePath
                console.log(2, fileStorageType.value)
                console.log(3, localFileStoragePath.value)
            } else {
                message("获取文件存储信息失败", 'error')
            }

        } catch (err) {
            console.error('Failed to fetch config:', err)
        } finally {
            console.log(des + " 获取状态变量信息 完成")
        }
    }

    return {
        fileStorageType,
        systemName,
        localFileStoragePath,
        systemDescription,
        updateConfig
    }
})


// 系统初始化
async function sysInit() {

    // 注册所有图标
    registerIcon()

    // 初始化拦截器
    initAxiosInterceptors(router)

    // 动态加载菜单
    await loadDynamicMenus();

    // 主Pinia 库更新参数
    await useMainStore().updateConfig("main.ts")
}

// 系统初始化
await sysInit();

// 注册插件
try {
    app.use(router)
} catch (error) {
    console.error('应用初始化失败:', error);
}


app.mount('#app')

export {
    isAppCollapsed,
    MainMenuItems,
    sysInit,
    useMainStore
}
